﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using RBS.Web.API.Models;

namespace RBS.Web.API.Areas.User.Controllers
{
    /// <summary>
    /// 手机订单
    /// </summary>
    public class ApiOrderDetailController : ApiController
    {
        private ApiContext db = new ApiContext();  
        // POST api/apiorderdetail
        /// <summary>
        /// 
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public JsonData Post([FromBody]OrderTemp model)
        {
            var jsonData = new JsonData();
            if (ModelState.IsValid)
            {
               // var orderTemp = new RBS.Core.Model.D_Order_Details {OrderId = model.OrderId, UId = model.UserId};  
                foreach (var item in model.CookBook)
                {
                    var cook = db.HotelCookbook.Find(item.Cid); 
                    var cookCount = Convert.ToInt32(cook.EstimateClear);

                    if (item.Num > cookCount && cookCount > 0)
                    {
                        jsonData.Success = false;
                        jsonData.Error = cook.Name+"库存数量不足";
                        return jsonData;
                    } 
                    for (int i = 0; i < item.Num; i++)
                    {
                        if (cookCount == 0)
                        { 
                            continue; 
                        } 
                        cookCount--;  
                        var orderTemp = new RBS.Core.Model.D_Order_Details
                            {
                                OrderId = model.OrderId,
                                UId = model.UserId,
                                HCId = item.Cid,
                                Num = 1,
                                IsGuest = 0,
                                State =1,
                                DisAmount = cook.Discount,
                                CName = cook.Name,
                                Price = cook.Price,
                                OperateDate=DateTime.Now
                            };
                        db.OrderDetails.Add(orderTemp);
                        db.SaveChanges();  
                    }  
                }
                jsonData.Success=true;
            }
            else
            {

                 jsonData.Success = false;
            }
            return jsonData;
        } 
    }

   
}
